﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Battle.View
{
    public class LinerProjectile : Projectile
    {
        Vector3 initPosition;
        Vector3 targetPosition;

        float flySpeed;
        Vector3 flyDir;
        bool isFlying = false;

        float deltaTime = 0f;

        protected override void Shoot()
        {
            var targetBC = BattleViewCtrl.GetInstance().GetBattleCharacter(targetPos);
            if (targetBC != null)
            {
                if (!string.IsNullOrEmpty(projResData.targetBindBone))
                {
                    targetPosition = targetBC.GetBonePosition(projResData.targetBindBone);
                }
                else
                {
                    targetPosition = targetBC.GetBeFoundBonePosition();
                }
            }
            else
            {
                targetPosition = BattleViewCtrl.GetInstance().GetPosition(targetPos);
            }

            transform.SetParent(creator.transform);
            transform.localPosition = Vector3.zero + projResData.initOffset;
            transform.SetParent(BattleViewCtrl.GetInstance().transform);

            initPosition = transform.localPosition;

            flySpeed = Vector3.Distance(initPosition, targetPosition) / projResData.projFlyTime;
            flyDir = (targetPosition - initPosition).normalized;
            deltaTime = 0f;
            isFlying = true;

            transform.localScale = Vector3.one;
            transform.localEulerAngles = Vector3.zero;
        }

        protected override void Tick0()
        {
            if (isFlying)
            {
                var newPos = transform.localPosition + flyDir * flySpeed * Time.deltaTime;
                transform.LookAt(newPos);
                transform.localPosition = newPos;

                deltaTime += Time.deltaTime;
                if (deltaTime >= projResData.projFlyTime)
                {
                    OnCollider();
                }
            }
        }

        protected override void OnCollider()
        {
            isFlying = false;
            isNeedRecycle = true;
        }

    }
}
